package system

import (
	"github.com/gin-gonic/gin"
	"server/global"
	comRequest "server/model/common/request"
	"server/model/common/response"
	sysModel "server/model/system"
	sysRequest "server/model/system/request"
	sysService "server/service/system"
)

type MenuApi struct {
}

//菜单首页列表
func (m *MenuApi) Index(c *gin.Context) {
	p := &sysRequest.SysMenuGetList{}
	if err := c.ShouldBind(p); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	//菜单分组列表
	groupList, _, err := sysService.MenuServiceApp.GetMenuGroupList(&sysRequest.SysMenuGroupList{})
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//菜单列表
	menuList, err := sysService.MenuServiceApp.GetMenuList(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	var menuTreeList []*sysModel.SysMenu
	//转换为树结构数据
	if p.Name == "" {
		menuTreeOriginList := ([]*sysModel.SysMenu)(nil)
		for _, menu := range menuList {
			menuTreeOriginList = append(menuTreeOriginList, menu)
		}
		menuTreeList = sysService.MenuServiceApp.BuildTree(menuTreeOriginList)
	} else {
		menuTreeList = menuList
	}
	//权限列表
	permList, err := sysService.PermissionServiceApp.GetAll()
	permTreeList := sysService.PermissionServiceApp.BuildTree(permList)
	response.OkWithData(gin.H{
		"groupList": groupList,
		"menuList":  menuTreeList,
		"permList":  permTreeList,
	}, c)
}

// 菜单保存
func (m *MenuApi) Save(c *gin.Context) {
	p := &sysModel.SysMenu{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	rows, err := sysService.MenuServiceApp.SaveMenu(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(gin.H{
		"rows": rows,
	}, c)
}

//菜单删除
func (m *MenuApi) Destroy(c *gin.Context) {
	p := &comRequest.IdsReq{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	rows, err := sysService.MenuServiceApp.DelMenu(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(gin.H{
		"rows": rows,
	}, c)
}

// 设置排序
func (m *MenuApi) SetOrder(c *gin.Context) {
	p := &sysRequest.SysMenuSetOrder{}
	if err := c.ShouldBind(p); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err := sysService.MenuServiceApp.SetOrder(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(gin.H{
		"p": p,
	}, c)
}
